<!DOCTYPE html>
<%@ taglib prefix="s" uri="/struts-tags"%>
<s:set var="ok" value="%{getText(\"button.ok\")}" />
<s:set var="cancel" value="%{getText(\"button.cancel\")}" />
<s:set var="customerProfile" value="%{getText('title.customer.customerProfile')}" />
<s:set var="updateSuccessfulMsg"
  value="%{getText('info.update.successful', {getText('title.customer.customerProfile')})}" />
<s:set var="requiredMsg" value="%{getText('error.required')}" />
<link href="${pageContext.request.contextPath}/css/jquery-ui-combobox.custom.css" rel="stylesheet"
  type="text/css" />
<script type="text/javascript">
  function loadCity(region) {
    jQuery.ajax({
      url : '${pageContext.request.contextPath}/district/getCities.action',
      dataType : 'json',
      cache : true,
      async : false,
      data : {
        region : region
      },
      success : function(data) {
        var city = $('#city');
        city.empty();
        $('#city_combobox').val('');
        $.each(data.rows,function(idx,record) {
          city.append($('<option />').val(record.id).text(record.name));
        });
      }
    });
  }

  function loadRegion() {
<%--aynsc should be set to false in order to load init data from DB--%>
  jQuery.ajax({
      url : '${pageContext.request.contextPath}/district/getRegions.action',
      dataType : 'json',
      cache : true,
      async : false,
      success : function(data) {
        var region = $('#region');
        region.empty();
        $.each(data.rows,function(idx,record) {
          region.append($('<option />').val(record.id).text(record.name));
        });
      }
    });
  }

  function focusOnFirstElement() {
    setTimeout(function() {
      $('#dialog-form :input:visible:enabled:first').focus();
    },10);
<%-- we need to set some delay due to bug (delay in rendering) in IE  --%>
  }

  $(function() {
    $('#customerMsg').tooltip({
      tooltipClass : "ui-state-highlight"
    });
    loadRegion();
    $("#dialog-form")
        .dialog(
            {
              height : 540,
              width : 800,
              modal : true,
              buttons : {
                '<s:property value="#ok" />' : function() {
                  var id = $('#id').val();
                  if (id > 0) {
                    var bValid = $('#customer-form').valid();
                    if (bValid) {
                      jQuery.ajax({
                        url : '${pageContext.request.contextPath}/customer/updateCustomer.action',
                        type : 'POST',
                        dataType : 'json',
                        cache : false,
                        data : {
                          'customer.id' : $('#id').val(),
                          'customer.version' : $('#version').val(),
                          'customer.firstname' : $('#firstname').val(),
                          'customer.lastname' : $('#lastname').val(),
                          'customer.alias' : $('#alias').val(),
                          'customer.phone' : $('#phone').val(),
                          'customer.mobile' : $('#mobile').val(),
                          'customer.fax' : $('#fax').val(),
                          'customer.email' : $('#email').val(),
                          'customer.street' : $('#street').val(),
                          'customer.postalCode' : $('#postalCode').val(),
                          'customer.city.id' : $('#city option:selected').val()
                        },
                        success : function(data) {
                          var msg = '';
                          var status = data.status;
                          if (status == 'SUCCESS') {
                            msg = '<s:property value="#updateSuccessfulMsg"/>';
                            if (data.attrs.version) {
                              var version = data.attrs.version;
                              $('#version').val(version);
                            }
                            $('#listCustomer').trigger('reloadGrid');
                          } else if (status == 'ERROR') {
                            if (data.errors) {
                              var errors = data.errors;
                              for ( var i = 0; i < errors.length; i++) {
                                msg += errors[i];
                                if (i < errors.length - 1) {
                                  msg += ', ';
                                }
                              }
                            }
                          }
                          $('#customerMsg').attr('title',msg).tooltip('open');
                          setTimeout(function() {
                            $('#customerMsg').tooltip("close").attr("title","");
                          },1500);
                        }
                      });

                    }
                  } else {
                    $('#customerMsg')
                        .attr(
                            'title',
                            '<s:property value="getText(\"error.predefined.cannot.be.modified\", {getText(\"title.customer.customerProfile\")})" />')
                        .tooltip('open');
                    setTimeout(function() {
                      $('#customerMsg').tooltip("close").attr("title","");
                      $("#dialog-form").dialog("destroy");
                    },800);
                  }
                },
                '<s:property value="#cancel" />' : function() {
                  $(this).remove();
                }
              },
              close : function() {
                $(this).remove();
              }
            });
    $("#customerAccordion").multipleaccordion();
<%-- if we do formatting JSP, in the textarea will display whitespace in the value. escapeJavaScript is used to handle special character i.e: # --%>
  $('#street').val('<s:property value="%{customer.street}" escapeJavaScript="true" />');
    $('#region').val('<s:property value="%{customer.region.id}" />');
    loadCity('<s:property value="%{customer.region.id}" />');
    $('#city').val('<s:property value="%{customer.city.id}" />');
    $('#city').combobox();
    $("#region").combobox({
      error : function() {
        $('#city').empty();
      }
    });
    $("#region").change(function() {
      var value = $(this).find('option:selected').val();
      if (value != '') {
        loadCity(value);
      }
    });
    $('#customerAccordion > div > table td.LABEL').css({
      'width' : '95px'
    });
    $('input, select, textarea, button').not(':hidden').each(function(idx) {
      $(this).prop('tabindex',idx + 1);
    });
<%-- need to append form on the fly after rendering dialog otherwise, form will be removed --%>
  $('#dialog-form').wrap('<form id="customer-form">');
    $.validator.setDefaults({
      errorClass : 'ui-state-error',
      errorPlacement : function(error,element) {
        if (element.context.id.indexOf('_combobox') == -1) {
          error.insertAfter(element.parent().children(':last'));
        } else {
          error.appendTo(element.parent());
        }
      }
    });
    $('#customer-form').validate(
        {
          rules : {
            'customer.firstname' : {
              required : true
            },
            'customer.alias' : {
              required : true,
              minlength : 3
            },
            'customer.phone' : {
              required : true
            },
            'customer.mobile' : {
              required : true
            },
            'customer.street' : {
              required : true
            },
            'region_combobox' : {
              required : true
            },
            'city_combobox' : {
              required : true
            }
          },
          messages : {
            'customer.firstname' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.firstname\")}" />')
            },
            'customer.alias' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.customer.alias\")}" />'),
              minlength : jQuery.format('<s:property value="getText(\"error.minLength\")" />',
                  '<s:property value="%{getText(\"field.customer.alias\")}" />',3)
            },
            'customer.phone' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.phone\")}" />')
            },
            'customer.mobile' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.mobile\")}" />')
            },
            'customer.street' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.street\")}" />')
            },
            'region_combobox' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.region\")}" />')
            },
            'city_combobox' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.city\")}" />')
            }
          }
        });
    focusOnFirstElement();
  });
</script>
<div id="dialog-form" title='<s:property value="getText('title.edit.customer')"/>'>
  <div id="customerMsg"></div>
  <div id="customerAccordion">
    <h3>
      <s:property value="getText('title.customer.details')" />
    </h3>
    <div>
      <table>
        <tr>
          <td class="LABEL"><input type="hidden" id="version" name="customer.version"
            value="<s:property value="%{customer.version}" />" /> <input type="hidden" id="id"
            name="customer.id" value='<s:property value="%{#parameters[\"customer.id\"]}" />' /> <label
            for="firstname" class="mandatory"><s:property
                value="getText('field.contact.name')" /></label></td>
          <td><input type="text" id="firstname" name="customer.firstname"
            placeholder="<s:property
								value="getText('field.firstname')" />"
            value="<s:property value="%{customer.firstname}" />"> <input type="text"
            id="lastname" name="customer.lastname"
            placeholder="<s:property
								value="getText('field.lastname')" />"
            value="<s:property value="%{customer.lastname}" />"></td>
        </tr>
        <tr>
          <td class="LABEL"><label for="alias" class="mandatory"><s:property
                value="getText('field.customer.alias')" /></label>
          <td><input type="text" id="alias" name="customer.alias"
            value="<s:property value="%{customer.alias}" />"></td>
        </tr>
      </table>
    </div>
    <h3>
      <s:property value="getText('title.contact.information')" />
    </h3>
    <div>
      <table>
        <tr>
          <td class="LABEL"><label for="phone" class="mandatory"><s:property
                value="getText('field.phone')" /></label></td>
          <td><input type="text" id="phone" name="customer.phone"
            value="<s:property value="%{customer.phone}" />"></td>
        </tr>
        <tr>
          <td class="LABEL"><label for="mobile" class="mandatory"><s:property
                value="getText('field.mobile')" /></label></td>
          <td><input type="text" id="mobile" name="customer.mobile"
            value="<s:property value="%{customer.mobile}" />"></td>
        </tr>
        <tr>
          <td class="LABEL"><label for="fax"><s:property value="getText('field.fax')" /></label></td>
          <td><input type="text" id="fax" name="customer.fax"
            value="<s:property value="%{customer.fax}" />"></td>
        </tr>
        <tr>
          <td class="LABEL"><label for="email"><s:property
                value="getText('field.email')" /></label></td>
          <td><input type="text" id="email" name="customer.email"
            value="<s:property value="%{customer.email}" />"></td>
        </tr>
      </table>
    </div>
    <h3>
      <s:property value="getText('title.address')" />
    </h3>
    <div>
      <table>
        <tr>
          <td class="LABEL"><label for="street" class="mandatory"><s:property
                value="getText('field.street')" /></label></td>
          <td><textarea cols="30" rows="5" id="street" name="customer.street"></textarea></td>
        </tr>
        <tr>
          <td class="LABEL"><label for="postalCode"><s:property
                value="getText('field.postalCode')" /></label></td>
          <td><input type="text" id="postalCode" name="customer.postalCode"
            value="<s:property value="%{customer.postalCode}" />"></td>
        </tr>
        <tr>
          <td><label for="region" class="mandatory"><s:property
                value="getText('field.region')" /></label></td>
          <td><select id="region" name="customer.region"></select></td>
        </tr>
        <tr>
          <td class="LABEL"><label for="city" class="mandatory"><s:property
                value="getText('field.city')" /></label></td>
          <td><select id="city" name="customer.city"></select></td>
        </tr>
      </table>
    </div>
  </div>
</div>